What is IoC or DI ?

IoC stands for Inversion of Control, or DI, Dependency Injection. The term was founded by Martin Fowler, and is now currently supported by several IoC containers, such as Pico, XWork and Spring. IoC allows us to reduce the coupling between components and classes, makes unit testing a whole lot easier and generally promotes good coding style.

But what does it do ? Like the name suggests, it will inject certain dependant objects, rather than requiring the depending object to retrieve those objects itself.

An example

Suppose you need a JDBC connection (or Hibernate Session, or ..) in your WebWork Action to communicate with a database. Normally, you would be required to set up a Driver Manager, register a JDBC Driver and get a connection from it.

This is pseudo code, for demonstration only.
.. 
if (driverManager == null){
    driverManager = new DriverManager();
    driverManager.registerDriver("jdbc.Driver");
}
..
if (connection == null){
    ..
    connection = driverManager.getConnection("jdbc://host/db", username, password);
}
..

Anyway, you get the point. That's a lot of work to get that done. Now, you might want to use some static helper class, store the connection in a ThreadLocal or Session, .. wouldn't it be nice if we could turn this whole 'get the connection' into 'just give me a connection' ?
Confused again ?

Let's say we develop an Interface that will contain a setter for a JDBC connection:

public interface JDBCConnectionAware {
    public void setJDBCConnection( JDBCConnection connection );
}

Now, if we have a class that implements this interface, we have a binding contract that allows us to set a JDBCConnection object on that depending object.

public class MyAction implements JDBCConnectionAware {
    public JDBCConnection connection;
    ..
    public String execute() {
        ..
        connection.prepareStatement(".."); //here we use the connection object
        ..
        return Action.SUCCESS;
    }
    ..
    //as required by the implemented JDBCConnectionAware interface
    public void setJDBCConnection(JDBCConnection connection){
        this.connection = connection;
    }
}

So, if look at this example, you see that we do not have to get the connection object from somewhere, nor set it up. We just assume that someone will 'give' us a connection, or 'inject' it. That 'someone' will be our IoC container.
The IoC container will take care of instantiating objects and singletons, and when it finds a object to be implementing a certain interface, it will do the injection of the dependency.

This example is meant to demonstrate the injection. The loose coupling and easy testing is explained a whole lot better by Martin Fowler's examples.

Example in XWork

Coming soon.

Example in Spring

Coming soon.

Example in Pico

Coming soon.